<template>
  <ZZDialog class="settings-localtion" title="坐标定位" @close="callbackClose()">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon label-width="50px">
      <el-form-item label="经度" prop="pass">
        <el-input-number v-model="ruleForm.lon" :min="-180" :max="180" :precision="6" :step="0.0001" />
      </el-form-item>
      <el-form-item label="纬度" prop="checkPass">
        <el-input-number v-model="ruleForm.lat" :min="-90" :max="90" :precision="6" :step="0.0001" />
      </el-form-item>
      <el-form-item label="高度" prop="age">
        <el-input-number v-model="ruleForm.height" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
      </el-form-item>
    </el-form>
  </ZZDialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import ZZDialog from '@/common/ZZDialog.vue';
import type { FormInstance } from 'element-plus';
import { useViewer } from '@/stores/viewer';
import imgTest from '@/assets/location1.png';
let viewer: any;
let markerXY: any;
const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive({
  lon: 120.00963,
  lat: 30.276335,
  height: 50
});

const callbackClose = function () {
  if (markerXY) {
    viewer.entities.remove(markerXY);
    markerXY = null;
  }
};

onMounted(() => {
  viewer = useViewer().viewer;
});

function addundapteMaker(val: any) {
  const position = Cesium.Cartesian3.fromDegrees(val.x, val.y, val.z || 0);

  if (markerXY == null) {
    markerXY = viewer.entities.add({
      name: '坐标拾取',
      position: position,
      billboard: {
        image: imgTest,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // default: CENTER
        scale: 0.6
      }
    });
  } else {
    markerXY.position = position;
  }
  viewer.zz.centerAt({ x: val.x, y: val.y });
}
const centerAt = function () {
  if (viewer) {
    const mpt = viewer.zz.point2map({ x: Number(ruleForm.lon), y: Number(ruleForm.lat), z: Number(ruleForm.height) });

    addundapteMaker(mpt);
  }
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  centerAt();
  formEl.validate(valid => {
    if (valid) {
      console.log('submit!');
    } else {
      console.log('error submit!');
    }
  });
};
</script>

<style>
.settings-localtion {
  position: absolute;
  top: 100px;
  right: 150px;
  width: 200px;
}
</style>
